package jp.co.menox.tmapp.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import jp.co.menox.tmapp.dto.LendingInfoDto;
import jp.co.menox.tmcommon.model.Lending;
import jp.co.menox.tmcommon.model.LendingHistory;
import jp.co.menox.tmcommon.model.User;
import jp.co.menox.tmserver.dao.LendingDao;
import jp.co.menox.tmserver.dao.LendingHistoryDao;
import jp.co.menox.tmserver.dao.StatusDao;
import jp.co.menox.tmserver.dao.UserDao;

public class LendingInfoService {

    public List<LendingInfoDto> getLendingInfoList(String loginId) {
        
        //--------------------------------------------------------------------
        //  2. DB取得 & 返却用データ生成
        //--------------------------------------------------------------------
        // DAO取得
        UserDao userDao = new UserDao();
        LendingDao lendingDao = new LendingDao();
        
        // StatusMap取得
        Map<Integer, String> statusMap = new StatusDao().getStatusMap();
        
        // DateFormat定義
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        
        // ユーザーIDから貸し借り履歴を取得
        long lendingUser = new UserDao().getUserModel(loginId).getId();
        List<LendingHistory> lendingHistoryList = new LendingHistoryDao().getLendingListForApp(lendingUser);
        
        List<LendingInfoDto> lendingInfoList = new ArrayList<LendingInfoDto>();
        for (LendingHistory lendingHistory : lendingHistoryList) {
            User borrowingUser  = userDao.selectBg(lendingHistory.getBorrowingUser());   // 借用者情報取得
            Lending lending     = lendingDao.selectBg(lendingHistory.getLendingId());    // 借りたいもの情報取得
            
            // JSON変換用インスタンス生成
            // id, statusType, statusName, lendingName, count, userName, returnPlanDate
            LendingInfoDto lendingInfo = new LendingInfoDto(
                            lendingHistory.getId(), 
                            lendingHistory.getStatusType(), 
                            statusMap.get(lendingHistory.getStatusType()), 
                            lending.getName(), 
                            lendingHistory.getCount(), 
                            borrowingUser.getName(), 
                            dateFormat.format(lendingHistory.getReturnPlanDate())
            );
            lendingInfoList.add(lendingInfo);
        }

        return lendingInfoList;
    }
}